package es

import (
	"encoding/json"

	"gitee.com/mkwchecking/sr-core/yerr"
	es "github.com/olivere/elastic/v7"
)

type ESResult struct {
	result *es.SearchResult
	err    error
}

func (e *ESResult) Error() error {
	return e.err
}

func (e *ESResult) Result() *es.SearchResult {
	return e.result
}

func (e *ESResult) Hits() []*es.SearchHit {
	return e.result.Hits.Hits
}

func (e *ESResult) TotalHits() int64 {
	return e.result.Hits.TotalHits.Value
}

func (e *ESResult) Aggregations() es.Aggregations {
	return e.result.Aggregations
}

func (e *ESResult) Scan(res any) error {
	if e.TotalHits() == 0 {
		return yerr.ErrDataEmpty.Errorf("es result is empty")
	}

	resData := make([]byte, 0)
	resData = append(resData, '[')
	for i, hit := range e.Hits() {
		resData = append(resData, hit.Source...)
		if i < len(e.Hits())-1 {
			resData = append(resData, ',')
		}
	}
	resData = append(resData, ']')
	return json.Unmarshal(resData, res)
}
